<template>
  <div class="enter">
    <!--  头部  -->
    <ZJHeader>
      <template #left>
        <van-icon name="arrow-left" @click="handleReturn"/>
      </template>
      <template #right>
        <p @click="handleToggle">{{ currentType === "login" ? "注册" : "登录" }}</p>
      </template>
    </ZJHeader>
    <div class="enter-main">
      <p class="main-title">{{ currentType === "login" ? "登录" : "注册" }}</p>
      <!--   表单内容   -->
      <van-form label-width="4em" class="enter-form" @submit="onSubmit">
        <van-cell-group inset>
          <van-field
              autocomplete="off"
              v-model="formModel.username"
              name="username"
              label="用户名"
              placeholder="用户名"
              :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
              autocomplete="off"
              v-model="formModel.password"
              type="password"
              name="password"
              label="密码"
              placeholder="密码"
              :rules="[{ required: true, message: '请填写密码' }]"
          />
          <!--     确认密码和邮箱只有注册才有     -->
          <van-field
              autocomplete="off"
              v-if="currentType === 'register'"
              v-model="formModel.passwordAgain"
              type="password"
              name="passwordAgain"
              label="确认密码"
              placeholder="确认密码"
              :rules="[{ required: true, message: '请再次填写密码' }]"
          />
          <van-field
              autocomplete="off"
              v-if="currentType === 'register'"
              v-model="formModel.email"
              type="email"
              name="email"
              label="邮箱"
              placeholder="邮箱"
              :rules="[{ required: true, message: '请填写邮箱' }]"
          />
          <van-field
              autocomplete="off"
              v-model="formModel.code"
              name="code"
              placeholder="验证码"
              label="验证码"
              :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #extra>
              <img @click="handleCaptcha" class="captcha-img" :src="imgUrl?.base64Url" alt="">
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 20px;">
          <van-button round block type="primary" native-type="submit">
            {{ currentType === "login" ? "登录" : "注册" }}
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onDeactivated, onMounted, ref} from "vue";

import {Toast} from "vant";

import useMyModule from "../../../store/myModule";
import {ILoginForm, IRegisterForm} from "@/views/ZJMy/MyEnter/types";
import {useRoute, useRouter} from "vue-router";
import ZJHeader from "@/components/ZJHeader/ZJHeader.vue";
import useGlobalStore from "@/store/globalModule";
import {getImageInfo} from "@/utils/image";

// 初始化相关变量
const myModule = useMyModule()
const router = useRouter()
const currentType = ref("login")
// 保存表单信息
const formModel = ref({
  username: "",
  password: "",
  passwordAgain: "",
  email: "",
  code: ""
})
// 重置表单
const resetForm = () => {
  formModel.value = {
    username: "",
    password: "",
    passwordAgain: "",
    email: "",
    code: ""
  }
}
// 获取验证码
const imgUrl = ref()
const handleCaptcha = async () => {
  imgUrl.value = await getImageInfo("/api/captcha")
}
onMounted(async () => {
  await handleCaptcha()
})
// 提交
const onSubmit = async (submitForm: IRegisterForm | ILoginForm) => {
      if (currentType.value === "login") {
        const isLogin = await myModule.loginAction(submitForm, {
          needToast: true
        })
        const query = router.currentRoute.value.query
        if (isLogin) {
          const returnPath = query.return || "/my"
          await router.replace(returnPath as string)
        } else {
          await handleCaptcha()
        }
      } else {
        const {passwordAgain, ...needParams} = submitForm as IRegisterForm
        if (needParams.password !== passwordAgain) {
          return Toast.fail("两次密码不一致")
        }
        const isRegister = await myModule.registerAction(needParams)
        if (isRegister) { // 注册成功,重置表单，变到登录
          Toast.success("注册成功")
          currentType.value = "login"
          resetForm()
        }
        await handleCaptcha()
      }
    }
;
// 离开时重置
onDeactivated(() => {
  resetForm()
})
// 注册和登录切换
const handleToggle = () => {
  if (currentType.value === "login") {
    currentType.value = "register"
  } else {
    currentType.value = "login"
  }
}
// 返回按钮
const handleReturn = () => {
  if (history.state.back) {
    router.back()
  } else {
    router.replace("/my")
  }
}
</script>

<style scoped lang="less">
@import "src/assets/css/variable";
@import "src/assets/css/mixins";

.enter {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 888;
  background-color: #F7F8FA;

  .enter-header {
    height: 50px;
    box-sizing: border-box;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    font-size: 16px;
    align-items: center;
    background-color: @theme-color;
    color: #fff;

    .van-icon {
      font-size: 20px;
    }
  }

  .enter-main {
    margin: 30px 20px 0 20px;

    .main-title {
      font-size: 20px;
      margin-bottom: 20px;
    }

    .van-cell-group {
      margin: 0;
    }
  }

  .enter-form {
    width: 100%;

    .van-field {
      padding: 20px;
    }

    .captcha-img {
      width: 130px;
      height: 32px;
    }
  }
}

</style>
